export class MqttChannel {
    constructor(identity) {
        this.identity = identity;
    }

    connect() {
        let self = this
        const mqtt = require('@/common/js/mqtt.js')
        var options = {
            clean: true, // 保留回话

            connectTimeout: 4000, // 超时时间

            // 认证信息

            clientId: 'cn.lokei-1',
            username: '',
            password: '',
            topic: '',
            port: 1885
        }
        // #ifdef H5 
        this.client = mqtt.connect('ws:175.178.217.142:1885', options)
        // #endif 
        //app的连接是 'wx://' + url。
        //#ifdef MP-WEIXIN
        this.client = mqtt.connect('wx:175.178.217.142:1885', options)
        // #endif
        if (this.client !== null && this.client !== '' && this.client !== undefined) {
            this.client.on('connect', function () {
                self.client.subscribe(self.identity + '_heartbeat', { qos: 0 }, function (err, granted) {
                    // console.log(granted)
                })
            })

            this.client.on('disconnect', (error) => {

            })

            this.client.on('reconnect', (error) => {
                console.log('正在重连:', error)
            })

            this.client.on('error', (error) => {
                console.log('连接失败:', error)
            })
        }
    }

    end() {
        if(this.client !== null && this.client !== '' && this.client !== undefined && this.client.connected) {
            this.client.end()
        }
    }

}